﻿using System;
using System.Linq.Expressions;

namespace OneWorks.Extension
{
    /// <summary>
    /// String扩展
    /// </summary>
    public static class ExpressionExtensions
    {
        /// <summary>
        /// 获取属性的名称
        /// </summary>
        /// <param name="expr"></param>
        /// <returns></returns>
        public static string PropertyNameFor<T>(this Expression<Func<T, object>> expr)
        {
            var rtn = "";
            if (expr.Body is UnaryExpression)
            {
                rtn = ((MemberExpression)((UnaryExpression)expr.Body).Operand).Member.Name;
            }//出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!            
            else if (expr.Body is MemberExpression)
            {
                rtn = ((MemberExpression)expr.Body).Member.Name;
            }
            else
            {
                var body = expr.Body as ParameterExpression;
                if (body != null)
                {
                    rtn = body.Type.Name;
                }
            }
            return rtn;
        }
    }
}
